<?php
if(!defined('SABLOG_ROOT')) {
	exit('Access Denied');
}

// 检查浏览模式
if ($viewmode == 'normal') {
	$pagefile = 'normal';
	$pagenum = intval($options['normal_shownum']);
	$timeformat = $options['normaltime'];

	$query_sql = "SELECT a.articleid,a.cid,a.uid,a.stick,a.dateline,a.title,a.description,a.content,a.keywords,a.views,a.comments,a.attachments,a.trackbacks,a.readpassword,a.alias,c.name as cname,c.url as curl,u.username
		FROM {$db_prefix}articles a
		LEFT JOIN {$db_prefix}categories c ON c.cid=a.cid
		LEFT JOIN {$db_prefix}users u ON a.uid=u.userid
		WHERE a.visible='1'";

} elseif ($viewmode == 'list') {
	$pagefile = 'list';
	$pagenum = intval($options['list_shownum']);
	$timeformat = $options['listtime'];

	$query_sql = "SELECT a.articleid,a.stick,a.dateline,a.title,a.views,a.comments,a.alias FROM {$db_prefix}articles a WHERE a.visible='1'";
} elseif ($viewmode == 'home'){
	$pagefile = 'home';
	$pagenum = 10;
	$timeformat = $options['normaltime'];

	$query_sql = "SELECT a.articleid,a.cid,a.uid,a.stick,a.dateline,a.title,a.description,a.content,a.keywords,a.views,a.comments,a.attachments,a.trackbacks,a.readpassword,a.alias,c.name as cname,c.url as curl
		FROM {$db_prefix}articles a
		LEFT JOIN {$db_prefix}categories c ON c.cid=a.cid
		WHERE a.visible='1' AND (SELECT COUNT(*)+1 FROM {$db_prefix}articles WHERE cid=a.cid AND dateline>a.dateline ORDER BY dateline DESC )<=3";
}
if($page) {
	$start_limit = ($page - 1) * $pagenum;
} else {
	$start_limit = 0;
	$page = 1;
}

$timeshow = date("Y, F j",$timestamp);

$user = sax_addslashes($_GET['user']);
$uid = intval($_GET['uid']);
$item = sax_addslashes($_GET['item']);
$searchid = intval($_GET['searchid']);

// 查看用户发表的文章
if ($user || $uid) {
	if ($user) {
		$usr = $DB->fetch_one_array("SELECT userid, username,articles FROM {$db_prefix}users WHERE username='$user' LIMIT 1");
		$pageurl = getuserlink($user);
	} else {
		$usr = $DB->fetch_one_array("SELECT userid, username,articles FROM {$db_prefix}users WHERE userid='$uid'");
		$pageurl = getuserlink($uid, false);
	}
	if (!$usr) {
		message('用户不存在', './');
	}
	$total = $usr['articles'];
	$query_sql .= " AND a.uid='".intval($usr['userid'])."' ORDER BY a.dateline DESC LIMIT $start_limit, ".$pagenum;
	$navtext = '查看'.$usr['username'].'的文章';
	$options['title'] = settitle($navtext);
	//
// 查看tags的相关文章
} elseif ($item) {
	$tag = $DB->fetch_one_array("SELECT usenum,aids FROM {$db_prefix}tags WHERE tag='$item' LIMIT 1");
	if (!$tag) {
		message('记录不存在.', './');
	}
	$total = $tag['usenum'];
	$query_sql .= " AND a.articleid IN (".$tag['aids'].") ORDER BY a.dateline DESC LIMIT $start_limit, ".$pagenum;
	$pageurl = gettaglink(urlencode($item));
	$navtext = 'Tag: '.htmlspecialchars($item);
	$options['title'] = settitle($item);
// 查看搜索结果的文章
} elseif ($searchid) {
	$search = $DB->fetch_one_array("SELECT * FROM {$db_prefix}searchindex WHERE searchid='".$searchid."' AND expiration>'$timestamp'");
	if (!$search) {
		$DB->unbuffered_query("DELETE FROM {$db_prefix}searchindex WHERE expiration < '$timestamp'");
		message('您指定的搜索不存在或已过期,请返回.', './');
	}
	$options['permalink'] = 0;
	$total = $search['totals'];
	$query_sql .= " AND a.articleid IN (".$search['ids'].") ORDER BY a.".$search['sortby']." ".$search['orderby']." LIMIT $start_limit, ".$pagenum;
	$pageurl = '?action=article&amp;searchid='.$searchid;
	$navtext = '搜索: '.$search['keywords'];
// 查看首页文章
} else {
	if ($options['permalink']) {
		$pageurl = $options['url'].'page/';
	} else {
		$pageurl = $options['url'].'?action=article';
	}

	$navtext = '全部文章';
	$total = $stats['article_count'];
	// 检查是否设置分类参数
	$cid = intval($_GET['cid']);
	$curl = sax_addslashes($_GET['curl']);
	$cwhere = '';
	if ($cid || $curl) {
		if ($cid) {
			$r = $DB->fetch_one_array("SELECT name,url,articles FROM {$db_prefix}categories WHERE cid='$cid'");
			$query_sql .= " AND a.cid='$cid'";
		} else {
			$r = $DB->fetch_one_array("SELECT cid,name,url,articles FROM {$db_prefix}categories WHERE url='$curl' LIMIT 1");
			$query_sql .= " AND a.cid='".intval($r['cid'])."'";
		}
		$navtext = '分类: '.$r['name'];
		$total = $r['articles'];
		$pageurl = getcatelink($cid, $r['url']);
		$options['title'] = settitle($r['name']);
	}

	//不用再计算记录数量直接从缓存读取
	$getnum = false;
	// 检查是否设置$setdate参数
	if ($setdate && strlen($setdate) == 6) {
		$navtext = $setyear.'年'.$setmonth.'月的文章';
		$pageurl = getdatelink($setdate);
		if ($archivesdb[$setdate]) {
			$total = intval($archivesdb[$setdate]);
		} else {
			$getnum = true;
		}
		// 检查是否设置$setday参数
		$setday = intval($_GET['setday']);
		if ($setday && is_numeric($setday)) {
			$getnum = true;
			if ($setday > 31 || $setday < 1) {
				$setday = sadate('d');
			}
			$navtext = $setyear.'年'.$setmonth.'月'.$setday.'日的文章';
			$start = strtotime($setyear.'-'.$setmonth.'-'.$setday);
			$end = $start + 86400;
			$pageurl = $options['url'].'?action=article&amp;setdate='.$setdate.'&amp;setday='.$setday;
		}
		$options['title'] = settitle($navtext);
	}
	//*******************************//
	$startadd = $start ? " AND a.dateline >= '".correcttime($start)."' " : '';
	$endadd   = $end ? " AND a.dateline < '".correcttime($end)."' " : '';
	//*******************************//
	if($getnum) {
		$query = $DB->query("SELECT COUNT(*) FROM {$db_prefix}articles a WHERE a.visible='1' ".$startadd.$endadd);
		$total = $DB->result($query, 0);
	}
	//*******************************//
	if($viewmode == 'home') {
		$pagenum = 20;
	}
	$query_sql .= $startadd.$endadd." ORDER BY a.stick DESC, a.dateline DESC LIMIT $start_limit, ".$pagenum;
}
// 执行查询
if ($total) {
	require_once(SABLOG_ROOT.'include/func/attachment.func.php');
	$query = $DB->query($query_sql);
	$multipage = multi($total, $pagenum, $page, $pageurl);
	$articledb = array();
	while ($article = $DB->fetch_array($query)) {
		$article['url'] = getpermalink($article['articleid'], $article['alias'], 0, sadate('Y/m/d',$article['dateline']));
		$article['userurl'] = getuserlink($article['username']);

		//隐藏变量,默认模板用不着,方便那些做模板可以单独显示月份和号数的的朋友.
		$article['month'] = sadate('M', $article['dateline']);
		$article['day'] = sadate('d', $article['dateline']);

		$article['dateline'] = sadate($timeformat, $article['dateline']);
		$article['title'] = trimmed_title($article['title'], $options['title_limit']);

		if ($viewmode == 'normal') {
			if ($article['readpassword'] && ($_COOKIE['readpassword_'.$article['articleid']] != $article['readpassword']) && $sax_group != 1 && $sax_group != 2) {
				$article['allowread'] = 0;
			} else {
				$article['allowread'] = 1;
				if (empty($article['description'])) {
					//附件
					if ($article['attachments']) {
						$attachs= unserialize(sax_stripslashes($article['attachments']));
						if (is_array($attachs)) {
							foreach ($attachs AS $attach) {
								$a_path = $options['attachments_dir'].$attach['filepath'];
								if (file_exists(SABLOG_ROOT.$a_path)) {
									$a_ext = strtolower(getextension($attach['filename']));
									if ($a_ext == 'gif' || $a_ext == 'jpg' || $a_ext == 'jpeg' || $a_ext == 'png') {
										$imagesize = @getimagesize(SABLOG_ROOT.$a_path);
										$a_size = sizecount($attach['filesize']);
										$a_thumb_path = $options['attachments_dir'].$attach['thumb_filepath'];
										if ($attach['thumb_filepath'] && $options['attachments_thumbs'] && file_exists($a_thumb_path)) {
											$article['image'][$attach['attachmentid']]=array($attach['attachmentid'],$a_thumb_path,$a_size,$attach['thumb_width'],$attach['thumb_height'],$attach['downloads'],1,$attach['filename']);
										} else {
											// 如果缩略图不存在
											$size = explode('x', strtolower($options['attachments_thumbs_size']));
											$im = scale_image( array(
												"max_width"  => $size[0],
												"max_height" => $size[1],
												"cur_width"  => $imagesize[0],
												"cur_height" => $imagesize[1]
											));	$article['image'][$attach['attachmentid']]=array($attach['attachmentid'],$a_path,$a_size,$im['img_width'],$im['img_height'],$attach['downloads'],0,$attach['filename']);
										}
									} else {
										// 如果非图片文件
										$a_size = sizecount($attach['filesize']);	$article['file'][$attach['attachmentid']]=array($attach['attachmentid'],$attach['filename'],$a_size,$attach['downloads']);
									}
								}
							}
							//如果空,释放掉变量
							$attachmentids=array();

							$article['content'] = preg_replace("/\[attach=(\d+)\]/ie", "upload('\\1')", $article['content']);

							foreach($attachmentids as $key => $value){
								if($article['image'][$value]){
									unset($article['image'][$value]);
								}
								if($article['file'][$value]){
									unset($article['file'][$value]);
								}
							}
						}
					}
				} else {
					$article['content'] = $article['description'];
				}
				//处理PHP高亮
				$article['content'] = preg_replace("/\s*\[php\](.+?)\[\/php\]\s*/ies", "phphighlite('\\1')", $article['content']);

				//TAGS
				if ($article['keywords']) {
					$articletags = $tmark = '';
					$tagdb = explode(',', $article['keywords']);
					foreach($tagdb as $tag) {
						$tag = trim($tag);
						$articletags .= $tmark.'<a href="'.gettaglink(urlencode($tag)).'">'.htmlspecialchars($tag).'</a>';
						$tmark = ', ';
						$article['content'] = highlight_tag($article['content'], $tag);
					}
					$article['alltags'] = $articletags;
				}
			}
			$article['cateurl'] = getcatelink($article['cid'], $article['curl']);
		} elseif ($viewmode == 'home') {
			if ($article['readpassword'] && ($_COOKIE['readpassword_'.$article['articleid']] != $article['readpassword']) && $sax_group != 1 && $sax_group != 2) {
				$article['allowread'] = 0;
			} else {
				$article['allowread'] = 1;
				if (empty($article['description'])) {
					$article['content'] = mb_substr(strip_tags($article['content']),0,35,'UTF-8').'...';
				} else {
					$article['content'] = mb_substr(strip_tags($article['description']),0,35,'UTF-8').'...';
				}

				//TAGS
				if ($article['keywords']) {
					$articletags = $tmark = '';
					$tagdb = explode(',', $article['keywords']);
					foreach($tagdb as $tag) {
						$tag = trim($tag);
						$articletags .= $tmark.'<a href="'.gettaglink(urlencode($tag)).'">'.htmlspecialchars($tag).'</a>';
						$tmark = ', ';
						$article['content'] = highlight_tag($article['content'], $tag);
					}
					$article['alltags'] = $articletags;
				}
			}
			$article['cateurl'] = getcatelink($article['cid'], $article['curl']);
		}
		$articledb[]=$article;
		unset($articletags);
	}
	unset($article);
	$DB->free_result($query);

	//设置一个时间戳,一定时间内该时间戳有效.用于COOKIE防盗链
	scookie('viewarticle', $timestamp);

}

?>